<!-- src/pages/Exam.vue -->
<template>
  <el-container style="padding: 40px;">
    <el-main>
      <el-card shadow="never">
        <!-- 时间信息栏 -->
        <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
          <div>
            当前时间：<strong>{{ nowTime }}</strong>
          </div>
          <div>
            考试用时：<strong>{{ formatTime(elapsed) }}</strong>
            |
            剩余时间：<strong :style="{ color: remaining <= 60 ? 'red' : 'inherit' }">
              {{ formatTime(remaining) }}
            </strong>
          </div>
        </div>

        <!-- 答题区域居中美观 -->
        <div class="exam-box">
          <h3 class="exam-title">第 {{ current + 1 }} 题 / {{ questions.length }}（本题：{{ questions[current].score }} 分）</h3>
          <p class="exam-question"><span class="question-no">{{ current + 1 }}.</span> {{ questions[current].question }}</p>
          <!-- 单选题 -->
          <el-radio-group
            v-if="questions[current].type === 'single'"
            v-model="answers[current]"
            class="option-group"
          >
            <el-radio
              v-for="(opt, index) in questions[current].options"
              :label="opt[0]"
              :key="index"
              class="option-item"
            >
              {{ opt }}
            </el-radio>
          </el-radio-group>
          <!-- 多选题 -->
          <el-checkbox-group
            v-else
            v-model="answers[current]"
            class="option-group"
          >
            <el-checkbox
              v-for="(opt, index) in questions[current].options"
              :key="index"
              :label="opt[0]"
              class="option-item"
            >
              {{ opt }}
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <!-- 按钮 -->
        <div style="margin-top: 20px; text-align: center;">
          <el-button @click="prev" :disabled="current === 0">上一题</el-button>
          <el-button @click="next" :disabled="current === questions.length - 1">下一题</el-button>
          <el-button type="danger" @click="submitExam" style="float: right;">结束考试</el-button>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRouter } from 'vue-router'
import { questions as rawQuestions } from '../assets/questions.js'
import { ElMessageBox } from 'element-plus'

const router = useRouter()
const questions = rawQuestions.map(q => ({ ...q, score: q.score ?? 2 }))

const answers = ref(questions.map(q => q.type === 'single' ? null : []))
const current = ref(0)

const isSubmitted = ref(false)
const isCorrectList = ref(questions.map(() => true))

const examDuration = 50 * 60
const elapsed = ref(0)
const remaining = ref(examDuration)
const nowTime = ref(new Date().toLocaleTimeString())
let timer = null

// 计算已答题数量
const answeredCount = computed(() => {
  return answers.value.filter(answer => {
    if (Array.isArray(answer)) {
      return answer.length > 0 // 多选题至少选一个
    }
    return answer !== null && answer !== '' // 单选题不为空
  }).length
})

const formatTime = (seconds) => {
  const m = String(Math.floor(seconds / 60)).padStart(2, '0')
  const s = String(seconds % 60).padStart(2, '0')
  return `${m}:${s}`
}

onMounted(() => {
  timer = setInterval(() => {
    elapsed.value++
    remaining.value--
    nowTime.value = new Date().toLocaleTimeString()
    if (remaining.value <= 0) {
      submitExam()
    }
  }, 1000)
})

onBeforeUnmount(() => {
  clearInterval(timer)
})

const next = () => {
  if (current.value < questions.length - 1) current.value++
}
const prev = () => {
  if (current.value > 0) current.value--
}

const submitExam = async () => {
  // 检查是否答完所有题目
  if (answeredCount.value < questions.length) {
    const message = `还有 ${questions.length - answeredCount.value} 题未答完，请答完所有题目后再提交`
    ElMessageBox.alert(message, '提示', { confirmButtonText: '确定' })
    return
  }

  clearInterval(timer)
  isSubmitted.value = true
  let totalScore = 0
  const correctArr = []
  questions.forEach((q, index) => {
    let correct = false
    if (q.type === 'single') {
      if (answers.value[index] === q.answer) {
        totalScore += q.score
        correct = true
      }
    } else if (q.type === 'multiple') {
      if (
        Array.isArray(answers.value[index]) &&
        answers.value[index].length === q.answer.length &&
        answers.value[index].every(a => q.answer.includes(a))
      ) {
        totalScore += q.score
        correct = true
      }
    }
    correctArr.push(correct)
  })
  isCorrectList.value = correctArr

  const employeeId = localStorage.getItem('employeeId')

  await fetch('http://localhost:3000/api/submit-score', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      employeeId,
      duration: elapsed.value,
      score: totalScore
    })
  })

  router.push({
    path: '/result',
    query: {
      score: totalScore,
      answers: JSON.stringify(answers.value),
      correct: JSON.stringify(correctArr)
    }
  })
}
</script>

<style scoped>
.exam-box {
  margin: 0 auto;
  width: 400px;
  text-align: left;
  background: #fff;
  padding: 24px 32px 16px 32px;
  border-radius: 12px;
  box-sizing: border-box;
}
.exam-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 12px;
  text-align: center;
}
.exam-question {
  font-size: 18px;
  margin-bottom: 18px;
  font-weight: 500;
}
.question-no {
  font-weight: bold;
  color: #070707;
  margin-right: 6px;
  font-size: 20px;
}
.option-group {
  display: flex;
  flex-direction: column;
  gap: 14px;
  align-items: flex-start;
}
.option-item {
  font-size: 18px !important;
  line-height: 1.8;
  margin-left: 0 !important;
  text-align: left !important;
  width: 100%;
}
.explanation-box {
  margin-top: 18px;
}
</style>


